package org.simplextensions.ui;

import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.simplextensions.ui.preferences.IPreferences;

/**
 * 
 * 
 * @author Tomasz Krzyzak, <a
 *         href="mailto:tomasz.krzyzak@gmail.com">tomasz.krzyzak@gmail.com</a>
 * @since 26-05-2010 21:01:43
 */
public class ShellAttributesListener implements ControlListener {
	private final IPreferences iPreferences;
	private final Shell shell;

	public ShellAttributesListener(Shell shell, IPreferences iPreferences) {
		this.shell = shell;
		this.iPreferences = iPreferences;

		Integer width = iPreferences.getInteger("size-x");
		Integer height = iPreferences.getInteger("size-y");
		Integer x = iPreferences.getInteger("position-x");
		Integer y = iPreferences.getInteger("position-y");
		Boolean max = iPreferences.getBoolean("maximized");

		if (width != null && height != null)
			shell.setSize(width, height);
		if (x != null && y != null && Display.getDefault().getBounds().contains(x, y))
			shell.setLocation(x, y);
		if (max != null) {
			shell.setMaximized(max);
		}
	}

	public void controlResized(ControlEvent arg0) {
		Point p = shell.getSize();
		if (!shell.getMaximized()) {
			iPreferences.setInteger("size-x", p.x);
			iPreferences.setInteger("size-y", p.y);
		}
	}

	public void controlMoved(ControlEvent arg0) {
		Point p = shell.getLocation();

		iPreferences.setBoolean("maximized", shell.getMaximized());
		if (!shell.getMaximized()) {
			iPreferences.setInteger("position-x", p.x);
			iPreferences.setInteger("position-y", p.y);
		}
	}
}